<template>
  <div class="tag-container">
    <a-tag style="margin-right: 10px;" v-for="tag in tagValue" :key="tag" closable @close="close(tag)">
      {{tag}}
    </a-tag>
    <div v-if="!visible" @click="showInput" class="add-tag center-flex">+</div>
    <input ref="input" @change="change" @blur="blur" class="add-input" type="text" v-else>
  </div>
</template>

<script>
export default {
  props: {
    value: {
      type: Array
    }
  },
  watch: {
    value() {
      this.tagValue = this.value
    }
  },
  data() {
    return {
      visible: false,
      tagValue: this.value
    }
  },
  methods: {
    close(tag) {
      this.$emit('change', this.tagValue.filter(item => String(item) !== String(tag)))
    },
    change({ target: { value } }) {
      this.visible = false
      if (this.tagValue.some((item) => String(item) === String(value)) || !value) return
      this.$emit('change', [...this.tagValue, value])
    },
    blur({ target: { value } }) {
      if (!value) {
        this.visible = false
      }
    },
    showInput() {
      this.visible = true
      this.$nextTick(() => {
        this.$refs.input.focus()
      })
    }
  }
}
</script>

<style lang="scss">
.tag-container {
  display: flex;
  align-items: center;
  flex-wrap: wrap;
}
.ant-tag,
.add-tag {
  margin: 10px;
}
.add-tag {
  display: inline-block;
  width: 52px;
  height: 26px;
  padding: 0 8px;
  line-height: 22px;
  border: 1px dashed #1890ff;
  border-radius: 4px;
  text-align: center;
  color: #3296fa;
  cursor: pointer;
}
.add-input {
  margin: 10px;
  height: 26px;
  width: 130px;
  padding: 8px;
  line-height: 22px;
  border: 1px solid #eeeeee;
  border-radius: 4px;
}
</style>

